<template>
  <div class="px-5 py-4 bg-white">
    <el-row :gutter="0">
      <el-col :span="24" :xs="24">
        <!-- 标题 -->
        <HeadTitle text="科室管理"/>
      </el-col>
      <el-col :span="24" :xs="24">
        <!-- 搜索 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="科室名称" prop="deptName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入科室名称"
              clearable
              @keyup.enter="getList"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row :gutter="20" justify="space-between">
      <el-col :span="20">
        <el-button type="primary" icon="plus" @click=";(open = true), reset()">新增</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="0" class="mt-4">
      <el-col :span="24">
        <Table
          :column="tableColumn"
          :table-data="deptList"
          :option="option"
          @command="handleCommand"
        >
          <template #status="scope">
            <el-tag v-if="scope.row.status === '0'" size="mini" type="success">正常</el-tag>
            <el-tag v-if="scope.row.status === '1'" size="mini" type="danger">停用</el-tag>
          </template>
        </Table>
      </el-col>
    </el-row>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" v-model="open" width="480px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px" inline>
        <el-row>
          <el-form-item label="科室名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入科室名称" style="width: 340px"/>
          </el-form-item>

          <el-form-item label="负责人" prop="leader">
            <el-input
              v-model="form.leader"
              placeholder="请输入负责人"
              maxlength="20"
              style="width: 340px"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入联系电话"
              maxlength="11"
              style="width: 340px"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              maxlength="50"
              style="width: 340px"
            />
          </el-form-item>
          <el-form-item label="部门状态">
            <el-switch v-model="form.status" active-value="0" inactive-value="1"/>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(deptRef)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {addDept, listDept, updateDept, delDept, getDept} from '@/api/dept'
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus'
import {reactive, ref, toRefs} from 'vue'

const queryRef = ref()
const title = ref('')
const open = ref(false)

interface fromType {
  deptName: StrUn
  leader: StrUn
  phone: NumUn
  email: StrUn
  status: StrUn
  deptId?: NumUn
  hospitalId?: StrUn
}

interface queryType {
  pageNum: number
  pageSize: number
  deptName: string | undefined
  status: string | undefined
}

interface dataType {
  form: fromType
  queryParams: queryType
  rules: Recordable
}

const data = reactive<dataType>({
  form: {
    deptName: undefined, //部门名称
    leader: undefined, //负责人
    phone: undefined, //电话
    email: undefined, //邮箱
    status: '0', //状态
    hospitalId: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    deptName: undefined, //部门名称
    status: undefined //状态
  },
  rules: {
    deptName: [{required: true, message: '科室名称不能为空', trigger: 'blur'}],
    email: [
      {
        pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    phone: [
      {
        pattern: /^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur"
      }
    ]
  }
})

const {queryParams, form, rules} = toRefs(data)

//表格配置
const tableColumn = [
  {type: 'index', label: '序号', align: 'center', width: '100'},
  {prop: 'name', label: '科室名称', align: 'center'},
  {prop: 'leader', label: '负责人', align: 'center'},
  {prop: 'phone', label: '电话', align: 'center'},
  {prop: 'status', label: '状态', align: 'center', slot: 'status'},
  {prop: 'createTime', label: '创建时间', align: 'center', showOverflowTooltip: true},
  {
    label: '操作',
    align: 'center',
    buttons: [
      {name: '修改', type: 'edit', command: 'edit', link: true, icon: 'Edit'},
      {name: '删除', type: 'delete', command: 'delete', link: true, icon: 'Delete'}
    ]
  }
] as Table.Column[]

interface State {
  deptList: Array<object>
  option: Table.Option
}

const state = reactive<State>({
  deptList: [],
  option: {
    loading: true,
    showPagination: false,
    height: 630
  }
})
const {deptList, option} = toRefs(state)

/** 查询部门列表 */
const getList = () => {
  option.value.loading = true
  listDept(queryParams.value).then((res: any) => {
    deptList.value = res.data
    option.value.loading = false
  })
}

/** 重置按钮操作 */
const resetQuery = (queryRef: { resetFields: () => void }) => {
  queryRef.resetFields()
  getList()
}

/** 取消按钮 */
const cancel = (): void => {
  open.value = false
  reset()
}
/** 表单重置 */
const reset = (): void => {
  form.value = {
    deptId: undefined,
    deptName: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: '0'
  }
}

/** 提交按钮 */
const deptRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(() => {
          ElMessage.success('修改科室')
          open.value = false
          getList()
        })
      } else {
        addDept(form.value).then(() => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
      reset()
    } else {
      console.log('error submit!', fields)
    }
  })
}

//操作按钮
const handleCommand = (command: string | number, row?: any) => {
  const deptId: number = row?.deptId
  const deptName: string = row?.name
  switch (command) {
    //修改
    case 'edit':
      reset()
      getDept(deptId).then((res: any) => {
        form.value = res.data
        title.value = '修改科室'
        open.value = true
        form.value.hospitalId = res.data.hospitalIdStr
      })
      break
    case 'delete':
      //删除
      ElMessageBox.confirm('是否确认删除' + deptName + '？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delDept(deptId).then(() => {
            getList()
            ElMessage.success('删除成功')
          })
        })
        .catch(() => {
        })
      break
    default:
      break
  }
}

getList()
</script>
<style scoped lang="less"></style>
